package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.vo.ChatPrivateSessionVO;
import com.zenithmind.chat.service.ChatPrivateSessionService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 私聊会话控制器 - 遵循单一职责原则
 * 只负责私聊会话的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/private-sessions")
@RequiredArgsConstructor
@Validated
@Tag(name = "私聊会话管理", description = "私聊会话相关接口")
public class ChatPrivateSessionController {

    private final ChatPrivateSessionService chatPrivateSessionService;

    @PostMapping("/create")
    @Operation(summary = "创建私聊会话", description = "创建与指定用户的私聊会话")
    public Result<String> createSession(
            @Parameter(description = "目标用户ID") @RequestParam @NotBlank String targetUserId) {
        String userId = UserContext.getUserId();
        String sessionId = chatPrivateSessionService.createSession(userId, targetUserId);
        return Result.success(sessionId);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询会话列表", description = "分页查询当前用户的私聊会话列表")
    public Result<PageResult<ChatPrivateSessionVO>> getUserSessionPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        PageResult<ChatPrivateSessionVO> result = chatPrivateSessionService.getUserSessionPage(userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/list")
    @Operation(summary = "查询会话列表", description = "查询当前用户的所有私聊会话")
    public Result<List<ChatPrivateSessionVO>> getUserSessions() {
        String userId = UserContext.getUserId();
        List<ChatPrivateSessionVO> sessions = chatPrivateSessionService.getUserSessions(userId);
        return Result.success(sessions);
    }

    @GetMapping("/{sessionId}")
    @Operation(summary = "查询会话详情", description = "根据会话ID查询会话详细信息")
    public Result<ChatPrivateSessionVO> getSessionById(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        ChatPrivateSessionVO session = chatPrivateSessionService.getSessionById(sessionId, userId);
        return Result.success(session);
    }

    @GetMapping("/with-user/{targetUserId}")
    @Operation(summary = "查询与指定用户的会话", description = "查询当前用户与指定用户的私聊会话")
    public Result<ChatPrivateSessionVO> getSessionWithUser(
            @Parameter(description = "目标用户ID") @PathVariable @NotBlank String targetUserId) {
        String userId = UserContext.getUserId();
        ChatPrivateSessionVO session = chatPrivateSessionService.getSessionWithUser(userId, targetUserId);
        return Result.success(session);
    }

    @DeleteMapping("/{sessionId}")
    @Operation(summary = "删除会话", description = "删除指定的私聊会话")
    public Result<Boolean> deleteSession(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.deleteSession(sessionId, userId);
        return Result.success(result);
    }

    @PutMapping("/{sessionId}/top")
    @Operation(summary = "置顶会话", description = "设置会话的置顶状态")
    public Result<Boolean> setSessionTop(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId,
            @Parameter(description = "是否置顶") @RequestParam Boolean isTop) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.setSessionTop(sessionId, isTop, userId);
        return Result.success(result);
    }

    @PutMapping("/{sessionId}/mute")
    @Operation(summary = "免打扰设置", description = "设置会话的免打扰状态")
    public Result<Boolean> setSessionMute(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId,
            @Parameter(description = "是否免打扰") @RequestParam Boolean isMuted) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.setSessionMute(sessionId, isMuted, userId);
        return Result.success(result);
    }

    @PostMapping("/{sessionId}/clear-unread")
    @Operation(summary = "清除未读数", description = "清除会话的未读消息数")
    public Result<Boolean> clearUnreadCount(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.clearUnreadCount(sessionId, userId);
        return Result.success(result);
    }

    @GetMapping("/{sessionId}/unread-count")
    @Operation(summary = "查询未读消息数", description = "查询指定会话的未读消息数")
    public Result<Integer> getUnreadCount(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        Integer unreadCount = chatPrivateSessionService.getUnreadCount(sessionId, userId);
        return Result.success(unreadCount);
    }

    @GetMapping("/total-unread-count")
    @Operation(summary = "查询总未读数", description = "查询当前用户的总未读消息数")
    public Result<Integer> getTotalUnreadCount() {
        String userId = UserContext.getUserId();
        Integer totalUnreadCount = chatPrivateSessionService.getTotalUnreadCount(userId);
        return Result.success(totalUnreadCount);
    }

    @PostMapping("/{sessionId}/update-last-message")
    @Operation(summary = "更新最后消息", description = "更新会话的最后一条消息信息")
    public Result<Boolean> updateLastMessage(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId,
            @Parameter(description = "消息ID") @RequestParam @NotBlank String messageId) {
        Boolean result = chatPrivateSessionService.updateLastMessage(sessionId, messageId);
        return Result.success(result);
    }

    @GetMapping("/active")
    @Operation(summary = "查询活跃会话", description = "查询当前用户的活跃私聊会话")
    public Result<List<ChatPrivateSessionVO>> getActiveSessions(
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<ChatPrivateSessionVO> sessions = chatPrivateSessionService.getActiveSessions(userId, limit);
        return Result.success(sessions);
    }

    @GetMapping("/top")
    @Operation(summary = "查询置顶会话", description = "查询当前用户的置顶私聊会话")
    public Result<List<ChatPrivateSessionVO>> getTopSessions() {
        String userId = UserContext.getUserId();
        List<ChatPrivateSessionVO> sessions = chatPrivateSessionService.getTopSessions(userId);
        return Result.success(sessions);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索会话", description = "根据关键词搜索私聊会话")
    public Result<List<ChatPrivateSessionVO>> searchSessions(
            @Parameter(description = "关键词") @RequestParam @NotBlank String keyword) {
        String userId = UserContext.getUserId();
        List<ChatPrivateSessionVO> sessions = chatPrivateSessionService.searchSessions(userId, keyword);
        return Result.success(sessions);
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除会话", description = "批量删除多个私聊会话")
    public Result<Boolean> batchDeleteSessions(@RequestBody List<String> sessionIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.batchDeleteSessions(sessionIds, userId);
        return Result.success(result);
    }

    @PostMapping("/batch-clear-unread")
    @Operation(summary = "批量清除未读", description = "批量清除多个会话的未读消息数")
    public Result<Boolean> batchClearUnreadCount(@RequestBody List<String> sessionIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.batchClearUnreadCount(sessionIds, userId);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "会话统计", description = "获取当前用户的私聊会话统计信息")
    public Result<Object> getSessionStatistics() {
        String userId = UserContext.getUserId();
        Object statistics = chatPrivateSessionService.getSessionStatistics(userId);
        return Result.success(statistics);
    }

    @PostMapping("/archive")
    @Operation(summary = "归档会话", description = "归档指定的私聊会话")
    public Result<Boolean> archiveSession(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.archiveSession(sessionId, userId);
        return Result.success(result);
    }

    @PostMapping("/unarchive")
    @Operation(summary = "取消归档", description = "取消归档指定的私聊会话")
    public Result<Boolean> unarchiveSession(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateSessionService.unarchiveSession(sessionId, userId);
        return Result.success(result);
    }

    @GetMapping("/archived")
    @Operation(summary = "查询归档会话", description = "查询当前用户的归档私聊会话")
    public Result<List<ChatPrivateSessionVO>> getArchivedSessions() {
        String userId = UserContext.getUserId();
        List<ChatPrivateSessionVO> sessions = chatPrivateSessionService.getArchivedSessions(userId);
        return Result.success(sessions);
    }
}
